<template>
  <van-button
    v-if="!isFollowed"
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    @click="onFollowed"
    :loading="followedLoading"
    loading-text="加载中..."
    >关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    round
    size="small"
    @click="onFollowed"
    :loading="followedLoading"
    loading-text="加载中..."
    >已关注</van-button
  >
</template>

<script>
import { deleteUserFollowed, addUserFollowed } from '@/api/user.js'
export default {
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, Object],
      required: true
    }
  },
  data () {
    return {
      // 关注按钮加载状态
      followedLoading: false
    }
  },
  // 修改v-model规则
  model: {
    prop: 'isFollowed',
    event: 'followed'
  },
  methods: {
    // 关注 取关
    async onFollowed () {
      // 按钮加载中
      this.followedLoading = true
      try {
        if (this.isFollowed) {
          // 取关
          await deleteUserFollowed(this.userId)
          this.$toast.success('取关成功')
        } else {
          // 关注
          await addUserFollowed(this.userId)
          this.$toast.success('关注成功')
        }
        // 改变数据
        this.$emit('followed', !this.isFollowed)
      } catch (err) {
        if (err.response && err.response.status === 400) {
          this.$toast.success('亲,不能关注自己哦')
        } else {
          this.$toast.success('操作失败')
        }
      }
      // 取消加载状态
      this.followedLoading = false
    }
  }
}
</script>

<style scoped lang='less'>
</style>
